﻿using Hospital.Utility.ApiResult;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Hospital.Model.DTO;
using Hospital.Utility._MD5;
using Hospital.IService;
using Hospital.Model.entity;

namespace Hospital.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class UserInfoController : ControllerBase
    {
        private readonly IUserInfoService iUserInfoService;
        private readonly IDoctorService iCreatorService;
        public UserInfoController(IUserInfoService iUserInfoService, IDoctorService iDoctorService)
        {
            this.iUserInfoService = iUserInfoService;
            this.iCreatorService = iDoctorService;
        }
        [HttpPost("login")]
        public async Task<ActionResult<ApiResult>> LoginUserInfo([FromBody] UserInfoDTO userInfoDTO)
        {
            var b = await iUserInfoService.FindAsync(c => c.Account == userInfoDTO.Account && c.Password == MD5Helper.MD5Encrypt32(userInfoDTO.Password));
            if (b != null) return ApiResultHelper.Success("success");
            return ApiResultHelper.Error("error");
        }
        [HttpPost("reg")]
        public async Task<ActionResult<ApiResult>> RegUserInfo([FromBody] UserInfo newUserInfo)
        {
            var data = await iUserInfoService.FindAsync(c => c.Account == newUserInfo.Account);
            if (data != null) return ApiResultHelper.Error("账号已存在");
            newUserInfo.Password = MD5Helper.MD5Encrypt32(newUserInfo.Password);
            newUserInfo.Permissions = "0";
            bool b = await iUserInfoService.CreateAsync(newUserInfo);
            var user = await iUserInfoService.FindAsync(c => c.Account == newUserInfo.Account);
            Doctor doctor = new Doctor()
            {
                UserInfoId = user.Id
            };
            await iCreatorService.CreateAsync(doctor);
            if (!b) return ApiResultHelper.Error("注册失败");
            return ApiResultHelper.Success("注册成功");
        }
        [HttpPut()]
        public async Task<ActionResult<ApiResult>> PutUserInfo([FromBody] UserInfo username)
        {
            var idClaim = this.User.FindFirst("Id");
            if (idClaim == null) return ApiResultHelper.Error("未找到用户ID");

            int id = Convert.ToInt32(idClaim.Value);
            var data = await iUserInfoService.FindAsync(id);
            if (data == null) return ApiResultHelper.Error("未找到用户");
            data = username;
            bool b = await iUserInfoService.EditAsync(data);
            if (b) return ApiResultHelper.Success("修改成功");
            return ApiResultHelper.Error("修改失败");
        }
        [AllowAnonymous]
        [HttpGet()]
        public async Task<ActionResult<ApiResult>> GetUserInfo(int id)
        {
            var user = await iUserInfoService.FindAsync(id);
            return ApiResultHelper.Success(user);
        }
    }
}
